package com.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.blog.pojo.User;
import com.blog.service.UserService;
import com.blog.utils.MessAgeAuThenTiCationCodeUtils;
import com.blog.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-04-15 16:03
 * FileName: UserController
 * Description:
 */
@RestController
@RequestMapping("user")
@Slf4j
@CrossOrigin
public class UserController extends BaseController{
    @Resource
    private UserService userService;

    /***
     * 用户登录
     * @param session
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login/{account}/{password}")
    public String login(HttpSession session, @PathVariable("account")String account, @PathVariable("password")String password ){
        log.info("用户验证登录:{}",account);
        User user=userService.Login(account, password);
        JSONObject jsonObject=new JSONObject();
        if(user==null){
            log.info("用户登录验证失败");
            jsonObject.put("success",false);
        }else{
            log.info("登录验证成功,用户ID传入会话");
            session.setAttribute("uid",user.getUid());
            jsonObject. put("success", true);
        }
        return jsonObject.toJSONString();
    }

    /***
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public String register(User user){
        user.setUid(UUIDUtils.getNumber());
        JSONObject object =new JSONObject();
        log.info("用户{}开始注册",user.getUsername());
        if(userService.register(user)==0){
            log.info("用户注册失败!");
            object.put("success",false);
        }else{
            log.info("用户注册成功,用户名为:{}   Uid为:{}",user.getUsername(),user.getUid());
            object.put("success",true);
        }
        return object.toJSONString();
    };

    /***
     * 用户注册短信验证
     * @param phone
     * @return
     */
    @GetMapping("/SendMessage/{phone}")
    public String sendMessage(@PathVariable("phone") String phone){
        JSONObject object=new JSONObject();
      String msage =MessAgeAuThenTiCationCodeUtils.sendMessage(phone);
      if(msage.equals("0")){
            log.info("短信验证码发送失败!");
            object.put("error","短信验证码发送失败");
      }else{
          log.info("短信发送成功,向前端发送短信验证码进行校验");
          object.put("phone",msage);
      }
      return object.toJSONString();
    }

    /***
     * 修改用户信息
     * @param session
     * @return
     */
    @PutMapping("/update")
    public String updateById(HttpSession session){
        JSONObject object=new JSONObject();
        log.info( "检查用户是否登录");
        Object uid =checkUser(session);
        User user=new User();
        if (uid != null) {
            log.info("获取用户信息");
            user=userService.queryById(Long.parseLong(session.getAttribute("uid").toString()));
        }else{
            object.put("success",false);
            return object.toJSONString();
        }
        log.info("修改用户信息:用户ID为:{}",user.getUid());
        //获取当前时间并修改对象的修改时间
        LocalDateTime localDateTime=LocalDateTime.now();
        user.setUpdateTime(localDateTime);
        int mes= userService.update(user);
        object.put("success",mes==1);
        return object.toJSONString();
    }

    /***
     * 用户修改头像
     * @param file
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("/updateAvatar")
    public String updateAvatarById(MultipartFile file, HttpSession session) throws IOException {
       JSONObject object= new JSONObject() ;
         log.info( "检查用户是否登录");
        Object uid =checkUser(session);
        User user=new User();
        if (uid != null) {
            log.info("获取用户信息");
            user=userService.queryById(Long.parseLong(session.getAttribute("uid").toString()));
        }else{
            object.put("success",false);
            return object.toJSONString();
        }
        //文件存储在本地的绝对路径
        String path = ("D:\\img\\");
      if(user.getAvatar().equals("默认头像.jpg")){
          //上传头像
      }else{
          //删除上次头像
          String avatar=user.getAvatar();
          String path2 = path + avatar;
          File newFile = new File(path2);
          if(newFile.exists() == true) {
              Boolean flag = false;
              flag= newFile.delete();
              if(flag){
                  log.info("成功删除图片:{}",file.getName());
              }else{
                  log.info("删除失败");
              }
          }else{
                log.info("图片不存在，终止操作");
          }
      }

        //判断是否上传了头像
        if (!file.isEmpty()) {
            log.info("进行头像的上传");
            //UUIDUtils为工具类，使用它随机生成一串字符（作用：上传图片时给图片名称拼接上去，防止图片名称重复）
            String n = UUIDUtils.create(20);
            String path2 = path + n + file.getOriginalFilename();
            //创建File对象，一会向该路径下上传文件
            File newFile = new File(path2);
            //MultipartFile的方法直接写文件
            file.transferTo(newFile);

            //给用户对象设置头像
            user.setAvatar(n + file.getOriginalFilename());
        }

        log.info("修改用户头像:用户ID为:{}",user.getUid());
        int mes= userService.updateAvatar(user);
        object.put("success",mes==1);
        //返回用户头像地址
        if(mes==1){
            object.put("fileName", user.getAvatar());
        }
        return object.toJSONString();
    }
    /***
     * 测试RedisHttpSession共享
     * @param request
     * @return
     */
    @GetMapping("/getid")
    public String getSessionuid(HttpServletRequest request){
        HttpSession session = request.getSession();
        return session.getId();
    }
}
